package com.nbsaas.boot;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.HexFormat;

public class HMACExample {
    public static void main(String[] args) {
        try {
            String message = "Hello, World!";  // 要加密的消息
            String key = "secretkey";  // 密钥

            // 创建 HMAC-MD5 实例
            Mac mac = Mac.getInstance("HmacMD5");
            SecretKeySpec secretKeySpec = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), "HmacMD5");
            mac.init(secretKeySpec);

            // 计算 HMAC
            byte[] hmac = mac.doFinal(message.getBytes(StandardCharsets.UTF_8));

            // 将 HMAC 转换为十六进制字符串
            String hmacHex = HexFormat.of().formatHex(hmac);
            System.out.println("HMAC-MD5: " + hmacHex);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
